package com.zhanglijie.theory.immutable.effective;

import java.util.ArrayList;

import jdk.nashorn.internal.ir.annotations.Immutable;
import lombok.ToString;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/7/25 0025 22:41
 * 实验证明 无法测试验证 immutable性能高于sync锁
 */
public class ImmutableEffecctTest {

    public static void main(String[] args) throws InterruptedException {
        ImmutableMode zhangsan = new ImmutableMode("ZHANGSAN");
        NoImmutableMode lisi = new NoImmutableMode("lisi");
        long start = System.currentTimeMillis();
        ArrayList<Thread> threads = new ArrayList<>();

        for (int j = 0; j < 5; j++) {
            Thread thread = new Thread(() -> {
                for (int i = 0; i < 200000; i++) {
                       zhangsan.toString();//6281  10662 局限性（count不再是immutable)
                    // lisi.toString();//4534(标量替换去锁）  10367
                }
            });
            thread.start();
            threads.add(thread);
        }
        for (int i = 0; i < 5; i++) {
            threads.get(i).join();
        }


        System.out.println((System.currentTimeMillis()-start));
    }
    static final class ImmutableMode {
        int count =1;
        final String name;
        public ImmutableMode(String name){
            this.name = name;
        }

        @Override
        public String toString() {
            count++;
            String res = "NoImmutableMode{" + "name='" + name + '\'' + '}';
            System.out.println(res+count);
            return res;
        }
    }

    static class NoImmutableMode{
        int count =1;
        private String name;
        public NoImmutableMode(String name){
            this.name = name;
        }

        @Override
        public synchronized  String toString() {
            count++;
            String res = "NoImmutableMode{" + "name='" + name + '\'' + '}';
            System.out.println(res+count);
            return res;
        }
    }
}
